package com.wqm.step;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.Test;

public class MySocketTCPPlus {

	@Test
	public void TCPClient() throws UnknownHostException, IOException {
		System.out.println("客户端。。。。。。");
		// while (true) {
		// 创建TCP客户端socket服务,指定要连接的ip和端口
		Socket socket = new Socket("127.0.0.1", 8888);
		// 获取该通道的输出流
		OutputStream outputStream = socket.getOutputStream();
		// 将数据写出到网络
		outputStream.write("你好，我又来了额。。".getBytes());
		// 获取服务端返回的数据,使用socket读取流
		InputStream inputStream = socket.getInputStream();
		byte[] buf = new byte[1024];
		int len = inputStream.read(buf);
		String text = new String(buf, 0, len);
		System.out.println(text);
		// 传输完成后，关闭资源
		socket.close();
		// }
	}

	@Test
	public void TCPServer() throws UnknownHostException, IOException {
		System.out.println("服务端。。。。。。");
		ServerSocket serverSocket = new ServerSocket(8888);
		// 获取连接过来的客户端对象。
		Socket socket = serverSocket.accept();
		String ip = socket.getInetAddress().getHostAddress();
		// 通过客户端对象获取socket流读取客户端发来的数据
		InputStream inputStream = socket.getInputStream();
		byte[] buf = new byte[1024];
		int len = inputStream.read(buf);
		String text = new String(buf, 0, len);
		System.out.println(ip + ":" + text);

		// 使用客户端socket对象给客户端返回数据
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write("收到".getBytes());

		socket.close();
		serverSocket.close();
	}

}
